/*
 * Copyright (C) 2015 Miquel Sas
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package traderlib.core.util;

import java.util.ArrayList;

/**
 * ArrayList utility functions.
 *
 * @author Miquel Sas
 */
public class ArrayListUtils {

	/**
	 * Private constructor. No instances have sense.
	 */
	private ArrayListUtils() {
	}	/**
	 * Compares an arraylist of comparable objects tothe argument object. Returns a negative integer, zero, or a
	 * positive integer as this list is less than, equal to, or greater than the specified argument list. Throws an
	 * UnsupportedOperationException if the argument is not an
	 *
	 * @param arrayList The source array list of comparable objects.
	 * @param o The object to compare.
	 * @return The compartion integer.
	 */


	/**
	 * Compares an arraylist of comparable objects to the argument object. Returns a negative integer, zero, or a
	 * positive integer as this list is less than, equal to, or greater than the specified argument list. Throws an
	 * UnsupportedOperationException if the argument is not an
	 *
	 * @param arrayList The source array list of comparable objects.
	 * @param o The object to compare.
	 * @return The compartion integer.
	 */
	public static int compareTo(ArrayList arrayList, Object o) {
		ArrayList<Comparable> comparable = null;
		try {
			comparable = (ArrayList) o;
		} catch (ClassCastException exc) {
			throw new UnsupportedOperationException("Not comparable type: " + o.getClass().getName());
		}
		if (arrayList.isEmpty() && comparable.size() > 0) {
			return -1;
		}
		if (arrayList.size() > 0 && comparable.isEmpty()) {
			return 1;
		}
		for (int i = 0; i < arrayList.size(); i++) {
			Comparable c1 = (Comparable)arrayList.get(i);
			Comparable c2 = (Comparable)comparable.get(i);
			int compare = c1.compareTo(c2);
			if (compare == 0) {
				if (i == arrayList.size() - 1 && i < comparable.size() - 1) {
					return -1;
				}
				if (i < arrayList.size() - 1 && i == comparable.size() - 1) {
					return 1;
				}
				continue;
			}
			return compare;
		}
		return 0;
	}

}
